06. Exercise: Display SleepQuality Data
L7 07 Implementing An Adapter SC
In SleepNightAdapter, onCreateViewHolder(), inflate the
text_item_viewlayout and return the ViewHolder.Get the
LayoutInflaterfromparent.contextand inflateR.layout.text_item_view.Remember to pass
falsetoattachParentsince theRecyclerViewwill take care of attaching it for us.override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TextItemViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val view = layoutInflater
.inflate(R.layout.text_item_view, parent, false) as TextView
return TextItemViewHolder(view)
}
In
SleepNightAdapter, add a custom setter todatathat callsnotifyDataSetChanged()and tell Kotlin to save the new value by settingfield = value.set(value) { field = value notifyDataSetChanged() }In
SleepTrackerFragment, create a newSleepNightAdapter, and use binding to associate it with theRecyclerView:
binding.sleepList.adapter = adapter
Create an observer on
sleepTrackerViewModel.nightsthat sets theAdapterwhen there is new data.LiveDataobservers are sometimes passednull, so make sure you check fornull.
Debugging tips
If your app compiles but doesn't work, here are a few things to check:
- Make sure you've added at least one night of sleep.
- Do you call
notifyDataSetChanged()inSleepNightAdapter? - Try setting a breakpoint to make sure it's getting called.
- Did you register an observer on
sleepTrackerViewModel.nightsinSleepTrackerFragment? - Did you set the adapter in
SleepTrackerFragmentwithbinding.sleepList.adapter = adapter? - Does
datainSleepNightAdapterhold a non-empty list? - Try setting a breakpoint in the setter and
getItemCount().
If you want to start at this step, you can download this exercise from: Step.02-Exercise-Display-Data.
You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.
Once you’re done, you can check your solution against the solution we’ve provided here: Step.02-Solution-Display-Data, or using this git diff.
Task Description:
Complete the following steps to create to implement the adapter.
Task Feedback:
Congrats! You've finished your RecyclerView adapter! Next we'll we'll take another look at onBindViewHolder to explore it further.
Reference Documentation